App = {
  web3Provider: null,
  contracts: {},

  shopArray: [],  //购买的东西数组
  payedmoney: 0,  //花费的钱

  init: async function () {
    // Load shopmal.
    let paramstr = decodeURI(location.search)
    let index = paramstr.indexOf("=")
    let params = JSON.parse(paramstr.substring(index+1))
    App.shopArray = params

    $.getJSON('../pets.json', function (data) {
      let account = 0
      var petsRow = $('#shopmal');
      var petTemplate = $('#shopTemplate');
      for (i = 0; i < params.length; i++) {   
        account = account + parseInt(data[params[i].id].price) * params[i].amount
        
        petTemplate.find('.img').attr('src', data[params[i].id].picture);
        petTemplate.find('.name').text(data[params[i].id].name);
        petTemplate.find('.date').text(data[params[i].id].date);
        petTemplate.find('.location').text(data[params[i].id].area);
        petTemplate.find('.amount').text('×'+params[i].amount);
        petsRow.append(petTemplate.html());
      }
      petsRow.find('.money').text(account)
      App.payedmoney = account
      $('.tail').find('.final').text(account)
    })
    
    

    return await App.initWeb3();
  },

  initWeb3: async function () {
    // Modern dapp browsers...
    if (window.ethereum) {
      console.log('1')
      App.web3Provider = window.ethereum;
      try {
        // Request account access
        await window.ethereum.enable();
      } catch (error) {
        // User denied account access...
        console.error("User denied account access")
      }
    }
    // Legacy dapp browsers...
    else if (window.web3) {
      console.log('2')
      App.web3Provider = window.web3.currentProvider;
    }
    // If no injected web3 instance is detected, fall back to Ganache
    else {
      console.log('3')
      App.web3Provider = new Web3.providers.HttpProvider('http://127.0.0.1:8545');
    }
    web3 = new Web3(App.web3Provider);

    return App.initContract();
  },

  initContract: function () {
    // 加载Adoption.json，保存了Adoption的ABI（接口说明）信息及部署后的网络(地址)信息，它在编译合约的时候生成ABI，在部署的时候追加网络信息
    $.getJSON('Adoption.json', function (data) {
      // 用Adoption.json数据创建一个可交互的TruffleContract合约实例。
      App.contracts.Adoption = TruffleContract(data);

      // Set the provider for our contract
      App.contracts.Adoption.setProvider(App.web3Provider);

      App.contracts.Adoption.deployed().then(function(instance){
        App.adoptionInstance = instance;
        return App.getShopcars();
      })
      // Use our contract to retrieve and mark the adopted pets
      //return App.markAdopted();
    });
    return App.bindEvents();
  },

  bindEvents: function () {
    $(document).on('click', '.back', App.jump);
    $(document).on('click', '.paymoney', App.pay);
  },

  pay: function () {
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log(error);
      }
      var account = accounts[0];    //默认第一个账户是用户地址，即外部账户地址
      var toaccount = accounts[1]   //默认第二个账户是商家地址
      // 发送交易支付
      console.log(App.shopArray)
      let shopArray = App.shopArray
      App.adoptionInstance.pay(App.payedmoney,{ from: account }).then(function(res) {
        
      var message = {from: account, to: toaccount , value: web3.toWei(App.payedmoney/10000, 'ether')};
      web3.eth.sendTransaction(message, (err, res) => {
        if(error){
          console.log('转账',error)
        }    
        console.log('result',res)
        App.adoptionInstance.addTransaction(res,{from:account}).then(function(){
          for (i = 0; i < shopArray.length; i++) { 
            App.adoptionInstance.buy(shopArray[i].id,shopArray[i].amount,account,{from:account}).then(function() {
              window.location.href="order.html";
            }).catch(function(err){
              console.log('buy',err)
            })
          } 
        }).catch(function(err){
          console.log('addtrans',err)
        })
        
      })
        
      }).catch(function(err){
        console.log('pay',err)
      })
     
    });
  },

  markAdopted: function (adopters, account) {
    var adoptionInstance;

    App.contracts.Adoption.deployed().then(function (instance) {
      adoptionInstance = instance;

      // 调用合约的getAdopters(), 用call读取信息不用消耗gas
      return adoptionInstance.getAdopters.call();
    }).then(function (adopters) {
      for (i = 0; i < adopters.length; i++) {
        if (adopters[i] !== '0x0000000000000000000000000000000000000000') {
          $('.panel-pet').eq(i).find('button').text('Success').attr('disabled', true);
        }
      }
    }).catch(function (err) {
      console.log(err.message);
    });
  },

  getShopcars: function () {
    // 获取用户账号
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log(error);
      }
      var account = accounts[0];
      
      // 发送交易添加购物车
      App.adoptionInstance.getShopcarsLen(account).then(function(len){
        if(len > 0){
          $('.account').text(len)
          $('.account').css("background-color","#ff5947");
          //App.loadShopcar(len-1);
        }
      }).catch(function(err){
        console.log('getshopcarlen',err)
      })
     
    });
  },

  addshop: function (event) {
    event.preventDefault();
    var shopId = parseInt($(event.target).data('id'));
    // 获取用户账号
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log('addshop',error);
      }
      var account = accounts[0];
      App.adoptionInstance.addshop(shopId, { from: account }).then(function(){
        return App.getShopcars();
      }).catch(function (err) {
        console.log('addshoperr',err.message);
      });
    });
  },

  loadShopcar: function(index) {
    web3.eth.getAccounts(function (error, accounts) {
      if (error) {
        console.log(error);
      }
      var account = accounts[0];
      App.adoptionInstance.shopcars(account, index).then(function(shopid) {        
        if (index - 1 >= 0) {
         
          App.loadShopcar(index - 1);
        }
      }).catch(function(err) {
          console.log(err)
      });
    })

  },

  jump: function() {
    // window.open("https://tt.wo.cn/auth/attachment/downloadForMobile?id=8064");
    window.location.href="shopcar.html";
  }

};

$(function () {
  $(window).on('load',function () {
    App.init();
  });
});

